#! /usr/bin/env python
# -*- coding: utf-8 -*-

import pygtk
import gtk
from gtk_ortho import GTKOrtho
from gtk_stereo import GTKStereo


import sys
from optparse import OptionParser

from plane import Plane

class NikolGTK():
    _state = 'new0'
    _pairs = []
    _curpair = []
    def __init__(self, density, incr, fdensity):
        # prepare an empty gird
        from grid_plane import PlaneGrid
        density_grid = PlaneGrid(size=[int(360/incr), int(90/incr)])
        for cell in density:
            a = Plane(cell[0],cell[1])
            density_grid.add(plane=a,val=cell[2])
        self.density=density_grid
        self.incr=incr

        self.win = gtk.Window()
        self.win.connect('destroy', gtk.main_quit)
        self.win.set_size_request(800,400)

        # vertical box that contain all the other widget 
        self.vbox = gtk.VBox()
        
        # horizontal box that contain ortho, stereo and list of conj pairs 
        self.hbox = gtk.HBox(False, 0)
        
        self.vbox.pack_start(self.hbox)
        
        self.statusbar = gtk.Statusbar()
        self.vbox.pack_start(self.statusbar,False,False,0) 

        self.ortho = GTKOrtho(density, incr)
        self.hbox.pack_start(self.ortho)

        self.stereo = GTKStereo(fdensity)
        self.hbox.pack_start(self.stereo)
        
        self.ortho.connect("motion_notify_event", self.mouse_over)
        self.ortho.connect("button_press_event", self.button_press)       
        self.ortho.set_events(gtk.gdk.EXPOSURE_MASK 
                              | gtk.gdk.LEAVE_NOTIFY_MASK
                              | gtk.gdk.BUTTON_PRESS_MASK
                              | gtk.gdk.POINTER_MOTION_MASK
                              | gtk.gdk.POINTER_MOTION_HINT_MASK)

        self.stereo.connect("button_press_event", self.button_press)
        self.stereo.connect("motion_notify_event", self.mouse_over)        
        self.stereo.set_events(gtk.gdk.EXPOSURE_MASK 
                              | gtk.gdk.LEAVE_NOTIFY_MASK
                              | gtk.gdk.BUTTON_PRESS_MASK
                              | gtk.gdk.POINTER_MOTION_MASK
                              | gtk.gdk.POINTER_MOTION_HINT_MASK)
        
        self.win.add(self.vbox)
        self.win.show_all()           

    def button_press(self, widget, event):
        dr, dp = widget.get_widget_coords(event.x, event.y)
        if [dr, dp] == [None, None]:
            return
        if self._state == "new0":
            self._state = "new1"
            self.ortho.put_a_pole(dr,dp)         
            self.ortho.queue_draw() 
            self.stereo.put_a_pole(dr,dp)         
            self.stereo.queue_draw()
            self._curpair.append([dr, dp])
        elif self._state == "new1":
            self._state = "edit0"
            self.ortho.put_a_pole(dr,dp)         
            self.ortho.queue_draw() 
            self.stereo.put_a_pole(dr,dp)         
            self._curpair.append([dr, dp])
            self.stereo.curpair=self._curpair
	    self.ortho.curpair=self._curpair
            self.stereo.queue_draw()
    
    def mouse_over(self, widget, event):
        dr, dp = widget.get_widget_coords(event.x, event.y)
        if [dr, dp] == [None, None]:
            return        
        # find density in clicked cell
        a = Plane(int(dr),int(dp))
        density = self.density.get(plane=a)
        self.statusbar.push(0,"%i %i, density: %i" % (dr, dp, density))
        if widget == self.ortho:
            pass
        elif widget == self.stereo:
            pass
    
    def main(self):
        gtk.main()

def readdensity(fname):
    f = open(fname, 'r')	
    lines = f.readlines(); f.close
    result = []
    size = float(lines.pop(0))
    for line in lines:
        valyes = [float(x) for x in line.split()]
        result.append(valyes)
    return result, size

def readfdensity(fname):
    f = open(fname, 'r')
    lines = f.readlines(); f.close
    result = []
    for line in lines:
        valyes = [float(x) for x in line.split()]
        result.append(valyes)
    return result

if __name__ == '__main__':
    optparser= OptionParser()
    optparser.add_option('-d', dest='dfile',
					help='Plot the density grid, which store in the file name, on the background')
    optparser.add_option('-f', dest='ffile',
					help='Plot the flat density grid, which store in the file name, on the background')				
    options, args = optparser.parse_args(sys.argv[1:])
    
    # Parse the density grid file
    density, size = None, None
    if options.dfile:
	    density, size = readdensity(options.dfile)
    if options.ffile:
        fdensity = readfdensity(options.ffile)   

    # start GUI
    a = NikolGTK(density, size, fdensity)    
    a.main()
    
